package com.ws.client;

import com.alibaba.fastjson.JSONObject;
import com.ws.client.other.InputSave;
import com.ws.client.other.VBean;
import com.ws.client.other.WinClientBean;
import com.ws.client.utils.FileUtils;
import com.ws.client.utils.LocalStorageUtils;
import com.ws.client.utils.LogHelper;
import com.ws.client.utils.RandomStringGenerator;
import org.java_websocket.enums.ReadyState;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.html5.LocalStorage;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.*;

import java.net.URI;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Main {
    public static boolean isClearDataPool = true;

    /**
     * 客户端程序
     */
    public static void client() throws IOException {

        //clearDataPool
        while (true) {
            LogHelper.debug("开始连接服务器,客户端ID:" + InputSave.clientId);
            try {
                BaseWebsocketClient baseWebsocketClient = new BaseWebsocketClient(new URI(InputSave.remoteHost + "/socket/baseClient"));
                baseWebsocketClient.connect();
                for (int i = 0; i < 10; i++) {
                    if (baseWebsocketClient.getReadyState().equals(ReadyState.OPEN)) {
                        LogHelper.debug("连接成功...");
                        break;
                    }
                    Thread.sleep(1000L);
                }
                //LogHelper.debug("11111111111...");
                if (baseWebsocketClient.isOpen()) {
                    InputSave.baseWebsocketClient = baseWebsocketClient;
                    //LogHelper.debug("连接服务器正常");

                    //JSONObject data = new JSONObject();
                    //data.put("token",InputSave.token_computer);
                    baseWebsocketClient.sendToServer("init", null);
                    //首次允许清空空闲池
                    if (isClearDataPool && InputSave.token_computer.contains("autoKey")) {
                        baseWebsocketClient.sendToServer("clearDataPool");
                        isClearDataPool = false;
                    }

                    int hc = 10;
                    while (true) {
                        Thread.sleep(1000);
                        hc++;
                        if (hc >= 20) {
                            //50秒发送一次心跳
                            LogHelper.debug("发送服务器心跳,检测连接中...当前客户端数量:" + InputSave.chromeDriverConcurrentHashMap.size());
                            baseWebsocketClient.sendToServer("heart");
                            hc = 1;
                        } else if (hc % 20 == 0) {
//                            if (InputSave.token_computer.contains("autoKey")) {
//                                InputSave.chromeDriverConcurrentHashMap.forEach((uuid, clientBean) -> {
//                                    //LogHelper.debug(uuid + "-->timeoutCheck:" + clientBean);
//                                    //检查是否服务端不存在  > 15分钟
//                                    if (new Date().getTime() - clientBean.getStartDate().getTime() > (900 * 1000)) {
//                                        JSONObject dataObject = new JSONObject();
//                                        dataObject.put("pid", uuid);
//                                        InputSave.baseWebsocketClient.sendToServer("checkClientExists", dataObject);
//                                        LogHelper.debug(uuid + "-->空闲客户端超时检查...");
//                                        //InputSave.closeWin(uuid);
//
//                                        //LogHelper.debug(uuid + "-->超时已自动关闭窗口");
//                                        // clientBean.getChromeDriver().close();
//                                    }
//                                });
//                            }
                        }
                    }
                } else {
                    LogHelper.debug("服务器连接失败,重连中...");
                }
                Thread.sleep(20000);  //原来的值是1000 ，lgl 增大间隔
            } catch (Exception e) {
                LogHelper.debug("服务器连接失败,重连中...");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        LogHelper.debug("客户端启动成功! 客户端版本:1.2.9");

        String currentDirectory = System.getProperty("user.dir");
        LogHelper.debug("当前执行路径:" + currentDirectory);
        InputSave.driver_path = currentDirectory + "\\chromedriver.exe";
        InputSave.cache_path = currentDirectory + "\\cache";
        //关闭日志
        Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);
        System.setProperty("webdriver.chrome.driver", InputSave.driver_path);

        //读取配置
        SeleniumHandler.readByLine("config.txt");
        //启动客户端
        client();

        //test();

    }

    public static void test() {
//        String tmpdir = System.getProperty("java.io.tmpdir").concat("Selenium\\").concat(RandomStringGenerator.generateRandomString(15).toUpperCase());
//        FileUtils.makeDir(tmpdir);
//        LogHelper.debug(tmpdir);
//        options.addArguments("--user-data-dir=" + tmpdir);

        ChromeOptions options = new ChromeOptions();
        // options.addArguments("--headless");

        //移除报错提示
        //options.addArguments("--allowed-ips");
        // options.addArguments("--single-process");
        //"                      –single-process"
        // options.addArguments("--start-minimized"); //无效
        options.addArguments("--no-zygote");

        options.addArguments("--disable-gpu"); // 谷歌文档提到需要加上这个属性来规避bug
        options.addArguments("--disable-software-rasterizer"); //禁用3D软件光栅化器
        // options.addArguments("--no-sandbox");// 为了让linux root用户也能执行
        // 优化参数
        options.addArguments("--disable-dev-shm-usage"); //解决在某些VM环境中，/dev/shm分区太小，导致Chrome失败或崩溃
        options.addArguments("--disable-plugins"); //禁用插件,加快速度
        options.addArguments("--disable-extensions"); //禁用扩展
        options.addArguments("--disable-popup-blocking"); //关闭弹窗拦截
        options.addArguments("--ignore-certificate-errors"); //  禁现窗口最大化
        options.addArguments("--allow-running-insecure-content");  //关闭https提示 32位
        ChromeDriver chromeDriver = new ChromeDriver(options);
        chromeDriver.get("https://baidu.com");
//        String qrData = "";
//        WebDriverWait wait = new WebDriverWait(chromeDriver, InputSave.wait_time);
//        while (true) {
//            // 等待元素可见并获取其属性值
//            try {
//                WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div._19vUU")));
//                String dataRefValue;
//                try {
//                    dataRefValue = element.getAttribute("data-ref");
//                } catch (Exception e) {
//                    continue;
//                }
//                if (!Objects.equals(qrData, dataRefValue)) {
//                    qrData = dataRefValue;
//                    if (dataRefValue != null && !dataRefValue.equals("null")) {
//                        //为空不传输
//                        LogHelper.debug("qrcode content change value: " + dataRefValue);
//                    }
//                }
//                String phoneNumber = LocalStorageUtils.getPhoneNumber(chromeDriver);
//                element.click();
//                if (phoneNumber != null) {
//                    LogHelper.debug("手机号：" + phoneNumber);
//                }
//            } catch (StaleElementReferenceException | TimeoutException e) {
//                LogHelper.debug("昵称：" + LocalStorageUtils.getNickname(chromeDriver));
//                LogHelper.debug("联系人：" + LocalStorageUtils.getContact(chromeDriver));
//            } catch (NoSuchSessionException e) {
//                LogHelper.debug("驱动已被率先关闭");
//                return;
//            } catch (Exception e) {
//                e.printStackTrace();
//                LogHelper.debug("系统发生异常");
//                return;
//            }
//        }
    }


}
